// 监听设置变化并重新高亮
chrome.storage.onChanged.addListener(function(changes) {
    if (changes.keywordGroups || changes.extensionEnabled) {
        clearHighlights();
        chrome.storage.sync.get(['extensionEnabled', 'keywordGroups'], function(result) {
            if (result.extensionEnabled !== false) {
                highlightKeywords(result.keywordGroups || []);
            }
        });
    }
});

// 页面加载完成后高亮关键词
chrome.storage.sync.get(['extensionEnabled', 'keywordGroups'], function(result) {
    if (result.extensionEnabled !== false) {
        const groups = result.keywordGroups || [];
        highlightKeywords(groups);
    }
});

// 高亮关键词函数
function highlightKeywords(groups) {
    groups.forEach(group => {
        const keywords = group.keywords.split(',').map(keyword => keyword.trim()).filter(Boolean);
        if (keywords.length === 0) return;

        const color = group.color;
        const textNodes = getTextNodes(document.body);

        textNodes.forEach(node => {
            const text = node.nodeValue;
            keywords.forEach(keyword => {
                const regex = new RegExp(`(${keyword})`, 'gi');
                if (regex.test(text)) {
                    const parent = node.parentNode;
                    const highlighted = text.replace(regex, 
                        `<span style="background-color: ${color}; padding: 0 2px; border-radius: 2px;">$1</span>`);
                    if (highlighted !== text) {
                        const temp = document.createElement('div');
                        temp.innerHTML = highlighted;
                        while (temp.firstChild) {
                            parent.insertBefore(temp.firstChild, node);
                        }
                        parent.removeChild(node);
                    }
                }
            });
        });
    });
}

// 获取所有文本节点
function getTextNodes(element) {
    const textNodes = [];
    const walk = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null);
    let node;
    while (node = walk.nextNode()) {
        textNodes.push(node);
    }
    return textNodes;
}

// 清除所有高亮
function clearHighlights() {
    const highlights = document.querySelectorAll('span[style*="background-color"]');
    highlights.forEach(highlight => {
        const parent = highlight.parentNode;
        const textNode = document.createTextNode(highlight.textContent);
        parent.replaceChild(textNode, highlight);
    });
}